//任务队列
class TaskQueue {
	constructor(config = {}){
		const { duration, start, end, auto = 1 } = config
		this.taskList = []
		//执行中
		this.executing = false
		//状态 0暂停 1开始
		this.status = auto
		//执行时长
		this.duration = duration
		//执行回调
		this.startCallback = start
		this.endCallback = end
	}
	
	add(tasks, duration){
		if(!tasks) return
		if(Array.isArray(tasks)){
			let _tasks = tasks.map(task => {
				return {
					info: task, duration
				}
			})
			this.taskList.push(..._tasks)
		}else{
			this.taskList.push({ info: tasks, duration })
		}
		
		this.start()
	}
	
	start(){
		if (this.status === 0 || this.executing || this.taskList.length === 0) return
		this.executing = true
		let { info, duration } = this.taskList.shift()
		if(this.startCallback){
			try{
				this.startCallback(info)
			}catch(e){
				console.log(e);
			}
		}
		let timer = setTimeout(async () => {
			clearTimeout(timer)
			timer = null
			
			//在执行完成前调用
			if(this.endCallback){
				await this.endCallback(info)
			}
			this.executing = false
			
			this.start()
		}, duration || this.duration)
	}
	
	play(){
		this.status = 1
		this.start()
	}
	
	pause(){
		this.status = 0
	}
	
	clear() {
		this.taskList = []
	}
	
	destroy(){
		this.clear()
		this.startCallback = null
		this.endCallback = null
	}
}

export default TaskQueue